<?php
/**
 * 前端页面基类
 * Created by Sublime Text 3.
 * @authors Rejeo (rejeo@qq.com)
 * @date    2018-05-05 23:09:21
 * @version $Id$
 */
namespace app\index\controller;

use think\Controller;

class Base extends Controller
{
    protected $city;
    protected $user;
    // 初始化城市数据,在需要使用的地方直接继承该类就好了
    public function _initialize()
    {
        $citys = model('city')->getNormalCitys();

        // 获取城市数据
        $this->getDefaultCity($citys);
        $cates = $this->getRecommendCates();
        // dump($cates);exit;

        $this->assign('citys', $citys);
        $this->assign('city', $this->city);
        $this->assign('cates', $cates);
        $this->assign('user', $this->getLoginUser());
    }

    // 获取默认城市
    public function getDefaultCity($citys)
    {
        $default = '';
        // dump($citys);exit;
        foreach ($citys as $city) {
            $city = $city->toArray();
            if (1===$city['is_default']) {
                $default = $city['uname'];
                break;
            }
        }

        $default = $default ? $default : 'beijing';
        if (session('cityname','','index') && !input('get.city')) {
            $cityname =  session('cityname','','index');
        } else {
            $cityname = input('get.city',$default, 'trim');
            session('cityname','','index');
        }
        $this->city = model('city')->where(['uname'=>$cityname])->find();
        // return $default;
    }

    // 获取登录数据
    public function getLoginUser()
    {
        if (!$this->user) {
            $this->user = session('user', '', 'index');
        }
        return $this->user;
    }

    // 获取首页推荐中的商品分类数据
    public function getRecommendCates()
    {

        if (cache('recomCates')) {
            return cache('recomCates');
        }
        $parentIds = $sedcateArr = $recomCates = [];
        // 获取顶级分类数据
        $cates = model('category')->getNormalRecommendCategoryByParentId(0,5);
        foreach($cates as $cate) {
            $parentIds[] = $cate->id;
        }
        // 获取二级分类的数据
        $sedCates = model('Category')->getNormalCategoryIdParentId($parentIds);
        foreach($sedCates as $sedcate) {
            $sedcateArr[$sedcate->parent_id][] = [
                'id' => $sedcate->id,
                'name' => $sedcate->name,
            ];
        }

        foreach($cates as $cat) {
            // recomCates 代表是一级分类和二级分类的数据，数组的第一个参数是一级分类的name,
            // 第二个参数是此一级分类下面的所有二级分类数据
            $recomCates[$cat->id] = [$cat->name, empty($sedcateArr[$cat->id]) ? [] : $sedcateArr[$cat->id]];
        }
        // 设置缓存数据
        cache('recomCates', $recomCates, 180);

        return $recomCates;
    }
}
